﻿
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Eis51.CampanyCMS.Business;
using Eis51.CampanyCMS.Business.Bus;

using Eis51.CampanyCMS.FrameWork;
using Eis51.CampanyCMS.Model.Bus;
using Eis51.CampanyCMS.Model;
using System.Text;



namespace Eis51.Web.Admin.ProductsManager
{
    /// <summary>
    /// NewProduct 的摘要说明。
    /// </summary>
    public partial class NewPurchase : BasePage
    {




        /// <summary>
        /// 产品ID
        /// </summary>
        protected string ProductId
        {
            get
            {
                if (Request["seqno"] == null)
                {
                    return "0";
                }
                return Request["seqno"].Trim();
            }
        }

        /// <summary>
        /// 绑定数据的源
        /// </summary>
        protected IList ImgData
        {
            get
            {
                if (ViewState["ImgData"] == null)
                {
                    ViewState["ImgData"] = new ArrayList();
                }
                return ViewState["ImgData"] as IList;
            }
            set
            {

                ViewState["ImgData"] = value;
            }
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {  

            if (!IsPostBack)
            {

                InitPage();
            }
        }


        private void InitPage()
        {
            string where = string.Format(" Licd={0} order by [Level] desc ", AppContext.LCID);
            IList listPurchase = PurchaseBLL.GetInstance().Search(where);
            StringBuilder sbExists = new StringBuilder();
            if (null != listPurchase && listPurchase.Count > 0)
            {
                Purchase tmpObj = null;
                foreach (var et in listPurchase)
                {
                    tmpObj = (Purchase)et;
                    if (sbExists.Length != 0)
                    {
                        sbExists.AppendFormat(",{0}", tmpObj.ProductID);
                    }
                    else
                    {
                        sbExists.AppendFormat("{0}", tmpObj.ProductID);
                    }
                }
            }

            this.ImgData = FileListBLL.GetInstance().GetFilesByProductId(this.ProductId, FileType.Product);
            PurchaseBLL.BindDropListTreeType2(drList, AppContext.GetCurrentName(), AppContext.LCID, sbExists.ToString());
            drList.Items.Insert(0, new ListItem("请选择", "0"));

            if (this.ProductId != "0")
            {
                Purchase f = PurchaseBLL.GetInstance().Get(new Purchase.Key(int.Parse(ProductId)));
                txtProductName.Text = f.Title;
                chkFirst.Checked = f.Isfirst > 0;
                txtProductDescr.Value = f.Descr;
                txtCode.Text = f.Code.Trim();
                txtKeyWord.Text = f.Keyword;
                txtShowIdx.Text = f.Level.ToString();//显示顺序
                BaseTools.SetListControl(drList, f.ProductID.ToString());
                
                //txtOldFilePath.Value = f.ImgBigPath;                                

                if (!string.IsNullOrEmpty(f.Indeximg))
                {
                    string file = string.Format("/UpLoadFile/{0}/img/", AppContext.CurrentAdministrator.Createby) + f.Indeximg;
                    string strfile = string.Format("<a target=_blank href='{0}' ><img src='{0}' width=50  height=50 border=0 ></a>", file);
                    
                }

            }
            Bind();
        }

        #region Web 窗体设计器生成的代码
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            //this.dgNews.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgNews_ItemDataBound);
            //this.dgNews.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgNews_ItemCommand);

        }
        #endregion

        protected void btnAdd_Click(object sender, System.EventArgs e)
        {
            string sss = string.Empty;// UploadFile.PostedFile.FileName;
            FileInfo info = new FileInfo(sss);
            string fileName = string.Empty;// FileListBLL.SaveProductImg(UploadFile, true);
            FileList fileList = new FileList();
            fileList.KeyType = ((int)FileType.Product).ToString();
            fileList.KeyValue = int.Parse(this.ProductId);
            fileList.FilePath = fileName;
            fileList.FileName = fileName;
            this.ImgData.Add(fileList);
            //this.txtPicCount.Value = this.ImgData.Count.ToString();
            Bind();


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgNews_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            
        }

        private void dgNews_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {

            //switch (e.CommandName)
            //{
            //    case "Delete":
            //        //删除对应的文件
            //        FileListBLL.GetInstance().DeleteProductImg(e.Item.Cells[3].Text, e.Item.Cells[0].Text);
            //        for (int i = ImgData.Count; i > 0; i--)
            //        {
            //            FileList o = ImgData[i - 1] as FileList;
            //            if (o.FilePath == e.Item.Cells[3].Text)
            //            {
            //                if (o.Seqno == 0)
            //                {
            //                    //删除图片。是新增的图片。没有在数据库里关联。所以这里要删除
            //                    FileListBLL.GetInstance().DeleteProductImg(o.FileName, "0");
            //                }
            //                ImgData.Remove(o);
            //            }
            //        }
            //        Bind();
            //        break;
            //    default:
            //        break;
            //}
        }

        private string GetSelectDefaultImg()
        {
            string def = "";
            //foreach (DataGridItem tmp in this.dgNews.Items)
            //{
            //    RadioButton selectExpresss = ((RadioButton)tmp.FindControl("selTemplate"));
            //    if (def == string.Empty && (tmp.ItemType == ListItemType.AlternatingItem || tmp.ItemType == ListItemType.Item))
            //    {
            //        def = tmp.Cells[3].Text;
            //    }
            //    if (selectExpresss != null && selectExpresss.Checked)
            //    {
            //        def = tmp.Cells[3].Text;

            //    }
            //}
            return def;
        }


        private void Bind()
        {
            //this.dgNews.Data = this.ImgData;
            //this.dgNews.DataBind();
            //if (ImgData.Count == 0)
            //{
            //    lblMsg.Text = "该产品没有上传图片,请上传!";
            //    lblMsg.Font.Size = FontUnit.XLarge;
            //    lblMsg.ForeColor = Color.Red;
            //    lblMsg.Visible = true;
            //    this.dgNews.Visible = false;
            //}
            //else
            //{
            //    lblMsg.Visible = false;
            //    this.dgNews.Visible = true;
            //}
            //this.txtPicCount.Value = this.ImgData.Count.ToString();
        }
        protected void btnSave_Click(object sender, System.EventArgs e)
        {
            Purchase p = null;

            if (drList.SelectedValue == "")
            {
                drList.Focus();
                Response.Write("<script>alert('请选择产品');</script>");
                return;
            }
            if (txtProductDescr.Value == "")
            {
                txtProductDescr.Focus();
                Response.Write("<script>alert('购买信息描述不能为空');</script>");
                return;
            }            
            if (this.ProductId != "0")
            {
                p = PurchaseBLL.GetInstance().Get(new Purchase.Key(int.Parse(this.ProductId)));
            }
            else
            {
                p = new Purchase();
            }

            p.Title = txtProductName.Text;
            p.Isfirst = chkFirst.Checked ? 1 : 0;
            p.Descr = txtProductDescr.Value;            
            p.Code = txtCode.Text.Trim();
            p.Keyword = txtKeyWord.Text;
            p.Level = int.Parse(txtShowIdx.Text.Trim());
            if (drList.SelectedValue != "")
            {
                p.ProductID = int.Parse(drList.SelectedValue);
            }
            p.Licd = AppContext.LCID;                        
            //p.ImgBigPath = GetSelectDefaultImg();
            p.ImgSmaillPath = p.ImgBigPath;            
            //string file = FileListBLL.GetInstance().SaveFile(UploadFile0);

            //if (!string.IsNullOrEmpty(file))
            //    p.Indeximg = file;


            PurchaseBLL.GetInstance().Submit(p, this.ImgData, null);
            //BuildPageHtml.BuildPage(p, @"~/XML/productinfo.xml");
            //BuildPageHtml.BuildPage(p, @"~/XML/productinfoEn.xml");
            btnReturn_Click(null, null);

        }

        protected void btnReturn_Click(object sender, System.EventArgs e)
        {
            if (Request.QueryString["r"] != null)
            {
                Response.Redirect(Request.QueryString["r"]);
            }
            else
            {
                Response.Redirect("PurchaseList.aspx");
            }
        }


    }
}
